import React from 'react';
import {Table, Card} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {injectIntl, formatMessage} from './intl';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {submitData, abandonData} from './api';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {kDClaimType, claimCompensationWay, urgencyLevel, kDClaimStatus, claimPartType, claimTransportType} from '../Enum';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {TABLE, PAGINATION_OPTIONS, FIXED_COLUMN_WIDTH, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, DATETIME_FORMAT} from '../constants';
const basePath = fetch.basePath || '';
const url = '/#/dcs/sales/saleProformaInvoiceKd/add';
export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    submitConfirm = id => {
        this.setState({
            loading: true
        });
        const record = this.props.data.find(d => d.id === id);
        submitData(id, record.rowVersion).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onChangeSort();
        });
    }
    abandonConfirm = id => {
        this.setState({
            loading: true
        });
        const record = this.props.data.find(d => d.id === id);
        abandonData(id, record.rowVersion).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onChangeSort();
        });
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };

    render() {
        const {pageIndex, pageSize, total, sortedColumnKey, data,
            permissions, sortedOrder, hasError, loading} = this.props;
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '申请单号'
            }),
            sorter: true,
            sortOrder: sortedColumnKey === 'code' && sortedOrder,
            render: (text, record) => <Link key="detail" to={routes.detail.format(record.id)}>{text}</Link>,
            dataIndex: 'code',
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'dealerCode',
            sorter: true,
            sortOrder: sortedColumnKey === 'dealerCode' && sortedOrder,
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.dealerName',
                defaultMessage: '总代名称'
            }),
            sorter: true,
            sortOrder: sortedColumnKey === 'dealerName' && sortedOrder,
            dataIndex: 'dealerName',
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.claimType',
                defaultMessage: '索赔类型'
            }),
            dataIndex: 'claimType',
            render: text => conventEnumValueToString(kDClaimType, text)
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.claimPartType',
                defaultMessage: '索赔配件类型'
            }),
            dataIndex: 'claimPartType',
            render: text => conventEnumValueToString(claimPartType, text)
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.actualCompensationWay',
                defaultMessage: '实际赔付方式'
            }),
            dataIndex: 'actualCompensationWay',
            render: text => conventEnumValueToString(claimCompensationWay, text)
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.actualTransportType',
                defaultMessage: '实际运输方式'
            }),
            dataIndex: 'actualTransportType',
            render: text => conventEnumValueToString(claimTransportType, text)
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.saleShipmentCode',
                defaultMessage: '发运单编号'
            }),
            sorter: true,
            sortOrder: sortedColumnKey === 'saleShipmentCode' && sortedOrder,
            dataIndex: 'saleShipmentCode',
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.batchNumber',
                defaultMessage: '批次'
            }),
            sorter: true,
            sortOrder: sortedColumnKey === 'batchNumber' && sortedOrder,
            dataIndex: 'batchNumber',
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.urgencyLevel',
                defaultMessage: '紧急程度'
            }),
            dataIndex: 'urgencyLevel',
            render: text => conventEnumValueToString(urgencyLevel, text)
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(kDClaimStatus, text)
        },
        {
            title: formatMessage({
                id: 'tablePanel.column.createTime',
                defaultMessage: '申请日期'
            }),
            sorter: true,
            dataIndex: 'createTime',
            sortOrder: sortedColumnKey === 'createTime' && sortedOrder,
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.firstApproveTime',
                defaultMessage: '初审日期'
            }),
            sorter: true,
            dataIndex: 'firstApproveTime',
            sortOrder: sortedColumnKey === 'firstApproveTime' && sortedOrder,
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.approveTime',
                defaultMessage: '复审日期'
            }),
            sorter: true,
            dataIndex: 'approveTime',
            sortOrder: sortedColumnKey === 'approveTime' && sortedOrder,
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'operate',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSION.update,
                        children: (
                            <Link key="update" to={routes.update.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.update',
                                    defaultMessage: '编辑'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                    },
                    {
                        id: PERMISSION.submit,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="submit"
                                placement="topLeft"
                                onConfirm={this.submitConfirm}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.message.submit',
                                    defaultMessage: '是否确认提交？'
                                })}>
                                <a>{formatMessage({
                                    id: 'tablePanel.operation.submit',
                                    defaultMessage: '提交'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.submit) && hasPermissions(r.options, PERMISSION.submit))
                    },
                    {
                        id: PERMISSION.firstapprove,
                        children: (
                            <Link key="firstapprove" to={routes.firstapprove.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.firstapprove',
                                    defaultMessage: '初审'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.firstapprove) && hasPermissions(r.options, PERMISSION.firstapprove))
                    },
                    {
                        id: PERMISSION.approve,
                        children: (
                            <Link key="approve" to={routes.approve.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.approve',
                                    defaultMessage: '复审'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.approve) && hasPermissions(r.options, PERMISSION.approve))
                    },
                    {
                        id: PERMISSION.partclaim,
                        children: (
                            <Link key="partclaim" to={routes.partclaim.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.partclaim',
                                    defaultMessage: '零件赔付'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.partclaim) && hasPermissions(r.options, PERMISSION.partclaim))
                    },
                    {
                        id: PERMISSION.reason,
                        children: (
                            <Link key="reason" to={routes.reason.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.reason',
                                    defaultMessage: '原因分析'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.reason) && hasPermissions(r.options, PERMISSION.reason))
                    },
                    {
                        id: PERMISSION.upgrade,
                        children: (
                            <Link key="upgrade" to={routes.upgrade.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.upgrade',
                                    defaultMessage: '升级讨论'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.upgrade) && hasPermissions(r.options, PERMISSION.upgrade))
                    },
                    {
                        id: PERMISSION.laborhourclaim,
                        children: <a href={`${basePath}${url}?id=${r.id}`} target="_blank" rel="noopener noreferrer">{
                            formatMessage({
                                id: 'tablePanel.operation.laborhourclaim',
                                defaultMessage: '工时赔付'
                            })
                        }</a>,
                        hidden: !(hasPermissions(permissions, PERMISSION.laborhourclaim) && hasPermissions(r.options, PERMISSION.laborhourclaim)),
                    },
                    {
                        id: PERMISSION.abandon,
                        children: (ref =>
                            <WrappedPopconfirm
                                key="abandon"
                                placement="topLeft"
                                onConfirm={this.abandonConfirm}
                                onVisibleChange={ref.setMenuVisible}
                                id={r.id}
                                title={formatMessage({
                                    id: 'tablePanel.message.abandon',
                                    defaultMessage: '是否确认作废？'
                                })}>
                                <a>{formatMessage({
                                    id: 'tablePanel.operation.abandon',
                                    defaultMessage: '作废'
                                })}</a>
                            </WrappedPopconfirm>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                    },
                ];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        return (
            <Card>
                <Table
                    className={'white-space-nowrap'}
                    columns={columns}
                    dataSource={data}
                    loading={loading || this.state.loading}
                    onChange={this.onChangeSort}
                    pagination={pagination}
                    rowKey="id"
                    locale={{
                        emptyText: hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                    }}
                    {...TABLE}/>
            </Card>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};
import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state),
});
const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


